
window.top.Historics.Thumbnail = {
	create: function (doc, maxThumbSize) {
		var canvas = doc.createElementNS("http://www.w3.org/1999/xhtml", "html:canvas");
		var context = canvas.getContext("2d");
			
		var root = doc.documentElement;
		
		// Find the window dimensions:
		var width = doc.defaultView.innerWidth;
		var height = doc.defaultView.innerHeight;
		
		var scale = 1.0;
		if(maxThumbSize!=null){
			var xScale = maxThumbSize/width;
			var yScale = maxThumbSize/height;
			scale = Math.min(xScale, yScale);
		}
		canvas.width = width * scale;
		canvas.height = height * scale;
		
		context.scale(scale, scale);
		
		context.drawWindow(doc.defaultView, 0, 0, width, height, "rgb(255,255,255)");
		
		return canvas;
	},
	saveThumbnail: function(file, doc, maxThumbSize) {
		if(!file.exists())
			FileIO.create(file);	
		var canvas = window.top.Historics.Thumbnail.create(doc, maxThumbSize);
		// create a data url from the canvas and then create URIs of the source and targets  
		var io = Components.classes["@mozilla.org/network/io-service;1"]
                     .getService(Components.interfaces.nsIIOService);
		var source = io.newURI(canvas.toDataURL("image/png"), "UTF8", null);
		var target = io.newFileURI(file);
		
		//Check if there is already a better thumbnail
		var length = window.top.Historics.Thumbnail.getThumbnailSize(file);
		if(source.spec.length < length) {
			//dump("Detected a better thumbnail\n");
			return 0;
		}
		
		// prepare to save the canvas data
		var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
                          .createInstance(Components.interfaces.nsIWebBrowserPersist);
  
		persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
		persist.persistFlags |= Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
  
		// save the canvas data to the file
		persist.saveURI(source, null, null, null, null, file);
		
		//var fileuri = "file:///"+File.path;
		var fileuri = target.asciiSpec;
		return fileuri
	},
	getThumbnailSize: function(File) {
		try {
			var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                       .createInstance(Components.interfaces.nsIFileInputStream);
			istream.init(File, -1, -1, false);

			var bstream = Components.classes["@mozilla.org/binaryinputstream;1"]
                       .createInstance(Components.interfaces.nsIBinaryInputStream);
			bstream.setInputStream(istream);

			var bytes = bstream.readBytes(bstream.available());
			
			return bytes.length;
		} catch (e) {
			//dump(" ----- Exception: "+e+"\n");
			return 0;
		}
	}
};